# TODO - zapisywanie wynikow testow jako warunkow?

import cal
import cnd
import time

import os
import re
import time

by_kind = {} # kind -> test

def load(name,cfg,job):
	kind=cfg['kind']
	return by_kind[kind](name,cfg,job)

def register(kind,cls):
	by_kind[kind]=cls

class Test:
	def __init__(self,name,cfg,job):
		self.name = name.lower()
		self.cfg = cfg
		self.job = job
		self.init()
	def init(self):
		pass # TODO
	def run(self):
		return 0 # TODO

class FileTest(Test):
	""" EXAMPLE:
	[test01]
	kind=file
	date=-1 work
	delay=60
	path=L:\incoming\%Y%m%d\report_123.csv
	"""
	def init(self):
		self.path = self.cfg['path'].replace('"','')
		self.delay = int(self.cfg.get('delay','30'))
		self.date = cal.offset(self.job.date,self.cfg.get('date','0'))
		d = time.strptime(self.date,"%Y%m%d")
		self.path = time.strftime(self.path,d)
	def run(self):
		if os.path.exists(self.path):
			mod_age = time.time()-os.stat(self.path)[8]
			if mod_age<self.delay:
				return 0
			try:
				open(self.path,'a') # check if not used
				return 1
			except Exception,e:
				pass
				print e
		return 0
register('file',FileTest)

class ScanTest(Test):
	def run(self):
		try:
			path = self.cfg['path'].replace('"','')
			pattern = self.cfg['pattern']
			min_cnt = int(self.cfg.get('min','1'))
			max_cnt = int(self.cfg.get('max','-1'))
			data = open(path,'r').read()
			cnt = len(re.findall(pattern,data))
			if max_cnt>=0 and cnt>max_cnt:
				return 0
			if cnt<min_cnt:
				return 0
			return 1
		except Exception,e:
			pass
			print e
		return 0
register('scan',ScanTest)

class CndTest(Test):
	def run(self):
		name = self.cfg['cnd']
		date = cal.offset(self.job.date,self.cfg.get('date','0'))
		date_to = cal.offset(self.job.date,self.cfg.get('date_to',self.cfg.get('date','0')))
		min_cnt = int(self.cfg.get('min','1'))
		max_cnt = int(self.cfg.get('max','-1'))
		if max_cnt>=0 and max_cnt<min_cnt:
			min_cnt=max_cnt
		cnt = 0
		for d in cnd.dates():
			if d<date or d>date_to:
				continue
			if cnd.exists(name,d):
				cnt += 1
			if max_cnt>=0 and cnt>max_cnt:
				return False
			if cnt>=min_cnt:
				return True
		return cnt>=min_cnt
register('cnd',CndTest)

##############################################################################

__test__ = {
'file':"""
	>>> class Job: pass
	>>> j=Job()
	>>> j.date='20110306'
	>>> t=FileTest("test00",{'path':"c:\\droga.txt",'date':'-1 all'},j)
	>>> print t.run()
	1
""",
'scan':"""
	>>> class Job: pass
	>>> j=Job()
	>>> j.date='20110306'
	>>> t=ScanTest("test00",{'path':"c:\\head.txt",'date':'-1 all','pattern':'o','min':'5'},j)
	>>> print t.run()
	1
"""
}

if __name__=="__main__":
	import doctest
	doctest.testmod(optionflags=doctest.ELLIPSIS)

"""
[test10]
kind=scan
path=c:\costam.txt
pattern=
min=
max=
"""